package com.ruoyi.system.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.system.domain.Code;
import com.ruoyi.system.domain.NewsClass;
import com.ruoyi.system.domain.NewsReport;
import com.ruoyi.system.service.ICodeService;
import com.ruoyi.system.service.INewsClassService;
import com.volcengine.ark.runtime.model.bot.completion.chat.BotChatCompletionRequest;
import com.volcengine.ark.runtime.model.bot.completion.chat.BotChatCompletionResult;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionContentPart;

import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;


import java.util.stream.Collectors;

import static com.ruoyi.common.utils.SecurityUtils.getUsername;

@RestController
@RequestMapping("/deepseek")
public class BotChatCompletionsExample {

    @Autowired
    private INewsClassService newsClassService;

    @Autowired
    private ICodeService codeService;

    private final String apiKey = "4fc2fa5d-72f8-46e3-a4b2-bf9813adf51e";

    /**
     * 打分
     *
     * @param codeText
     * @return
     */
    @GetMapping("/question")
    public String question(String codeText) {
        System.out.println("----- image input -----");
        String baseUrl = "https://ark.cn-beijing.volces.com/api/v3";
        ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS);
        Dispatcher dispatcher = new Dispatcher();
        ArkService service = ArkService.builder().dispatcher(dispatcher).connectionPool(connectionPool).baseUrl(baseUrl).apiKey(apiKey).build();

        final List<ChatMessage> messages = new ArrayList<>();
        final List<ChatCompletionContentPart> multiParts = new ArrayList<>();
        multiParts.add(ChatCompletionContentPart.builder().type("text").text(
                "作为一个专业的资深代码开发评审专家，针对以下代码给出你的评分（100分满分），并简述你的打分理由，50字以内，我的代码内容如下："+ codeText
        ).build());

        final ChatMessage userMessage = ChatMessage.builder().role(ChatMessageRole.USER)
                .multiContent(multiParts).build();
        messages.add(userMessage);

        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                // 指定您创建的方舟推理接入点 ID，此处已帮您修改为您的推理接入点 ID
                .model("ep-20250228142305-97hgk")
                .messages(messages)
                .build();

        StringBuffer stringBuffer = new StringBuffer();
        service.createChatCompletion(chatCompletionRequest).getChoices().forEach(choice -> {
            System.out.println(choice.getMessage().getContent());
            stringBuffer.append(choice.getMessage().getContent());
        });

        service.shutdownExecutor();
        return stringBuffer.toString();
    }

    /**
     * 首页问答大模型
     */
    @PostMapping("/questionhome")
    public JSONObject questionhome(@RequestBody NewsReport newsReport) {
        System.out.println("正在生成代码");
        String baseUrl = "https://ark.cn-beijing.volces.com/api/v3";
        ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS);
        Dispatcher dispatcher = new Dispatcher();
        ArkService service = ArkService.builder().dispatcher(dispatcher).connectionPool(connectionPool).baseUrl(baseUrl).apiKey(apiKey).build();

        final List<ChatMessage> messages = new ArrayList<>();
        final List<ChatCompletionContentPart> multiParts = new ArrayList<>();
        multiParts.add(ChatCompletionContentPart.builder().type("text").text(
                "作为一个专业的资深JavaScript前端开发专家，你要根据以下我的需求生成JS代码，要体现出你高超的专业技术，页面美观逻辑清晰可用，\r\n" +
                        " # 输出要求是：\r\n 只需要输出代码即可，所有生成的代码放到一个HTML文件中，要让我能够直接将代码复制到一个txt文件后，将后缀修改为HTML就可以直接打开。\r\n # 我的需求是：\r\n"+newsReport.getCaseName()
        ).build());

        final ChatMessage userMessage = ChatMessage.builder().role(ChatMessageRole.USER)
                .multiContent(multiParts).build();
        messages.add(userMessage);

        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                // 指定您创建的方舟推理接入点 ID，此处已帮您修改为您的推理接入点 ID
                .model("ep-20250228142305-97hgk")
                .messages(messages)
                .build();

        StringBuffer stringBuffer = new StringBuffer();
        service.createChatCompletion(chatCompletionRequest).getChoices().forEach(choice -> {
            System.out.println(choice.getMessage().getContent());
            stringBuffer.append(choice.getMessage().getContent());
        });

        service.shutdownExecutor();
        JSONObject stringStringHashMap = new JSONObject();
        stringStringHashMap.put("data", stringBuffer.toString());

        // 记录历史
        String scoreText = this.question(stringBuffer.toString());
        Code code = new Code();
        code.setInput(newsReport.getCaseName());
        code.setOutput(stringBuffer.toString());
        code.setScore(scoreText);
        String username = getUsername();
        code.setUserName(username);
        int i = codeService.insertCode(code);
        return stringStringHashMap;
    }



    // 生成事件基本信息
    @GetMapping("/getNews")
    public JSONObject getNews(String newsName) {
        StringBuffer stringBuffer = new StringBuffer();

        List<NewsClass> newsClasses = newsClassService.selectNewsClassList(new NewsClass());
        List<String> collect = newsClasses.stream().map(NewsClass::getName).collect(Collectors.toList());
        String classNameStrs = String.join(",", collect);

        ArkService service = ArkService.builder().apiKey(apiKey).build();

        System.out.println("\n----- standard request -----");
        final List<ChatMessage> messages = new ArrayList<>();
        final ChatMessage systemMessage = ChatMessage.builder().role(ChatMessageRole.SYSTEM).content("你是一个舆情信息获取专家").build();
        final ChatMessage userMessage = ChatMessage.builder().role(ChatMessageRole.USER).content("事件名称：" +newsName +",事件类型（case_category）从以下事件类型选取："+classNameStrs).build();
        messages.add(systemMessage);
        messages.add(userMessage);

        BotChatCompletionRequest chatCompletionRequest = BotChatCompletionRequest.builder()
                // 将<YOUR_BOT_ID>替换为您的应用ID
                .model("bot-20250219164543-trmvs")
                .messages(messages)
                .build();

        BotChatCompletionResult chatCompletionResult =  service.createBotChatCompletion(chatCompletionRequest);
        chatCompletionResult.getChoices().forEach(
                choice -> {
                    System.out.println(choice.getMessage().getContent());
                    stringBuffer.append(choice.getMessage().getContent());
                }
        );

        // 截取json
        String originalString = stringBuffer.toString();
        // 找到 { 首次出现的位置
        int startIndex = originalString.indexOf('{');
        // 找到 } 最后一次出现的位置
        int endIndex = originalString.lastIndexOf('}');

        if (startIndex != -1 && endIndex != -1 && startIndex < endIndex) {
            // 截取有效的 JSON 部分
            String jsonString = originalString.substring(startIndex, endIndex + 1);
            JSONObject jsonObject = JSONObject.parseObject(jsonString);
            System.out.println(jsonObject);
            System.out.println(jsonObject.get("case_name"));
            System.out.println(jsonObject.get("case_category"));
            return jsonObject;
        } else {
            System.out.println("未找到有效的 JSON 部分。");
        }
        return null;
    }

    // 生成舆情报告
    @GetMapping("/getReport")
    public String getReport(String newsName) {
        StringBuffer stringBuffer = new StringBuffer();

        ArkService service = ArkService.builder().apiKey(apiKey).build();

        System.out.println("\n----- standard request -----");
        final List<ChatMessage> messages = new ArrayList<>();
        final ChatMessage systemMessage = ChatMessage.builder().role(ChatMessageRole.SYSTEM).content("你是一个舆情信息获取专家").build();
        final ChatMessage userMessage = ChatMessage.builder().role(ChatMessageRole.USER).content("事件名称：" +newsName).build();
        messages.add(systemMessage);
        messages.add(userMessage);

        BotChatCompletionRequest chatCompletionRequest = BotChatCompletionRequest.builder()
                // 将<YOUR_BOT_ID>替换为您的应用ID
                .model("bot-20250228213205-w7mg6")
                .messages(messages)
                .build();

        BotChatCompletionResult chatCompletionResult =  service.createBotChatCompletion(chatCompletionRequest);
        chatCompletionResult.getChoices().forEach(
                choice -> {
                    System.out.println(choice.getMessage().getContent());
                    stringBuffer.append(choice.getMessage().getContent());
                }
        );
        return stringBuffer.toString();
    }

}
